package Sort;

import java.util.Arrays;

public class MergeSort {

    public static void merge(int[] array){
        mergeSort(array,0, array.length-1);
    }
    public static void mergeSort(int[] array,int left,int right){
        //分解
        if(left>=right){
            return;
        }
        int mid = (left+right)/2;
        mergeSort(array,left,mid);
        mergeSort(array,mid+1,right);
        //合并
        combine(array,left,right,mid);

    }
    public static void combine(int[] array,int left,int right,int mid){
        //两个有序数组合并
        int s1 = left;
        int s2 = mid+1;
        int[] tmp = new int[right-left+1];
        int k = 0;

        //进行数组的赋值
        while(s1<=mid && s2<=right){//保证两个数组内有数据
            if(array[s1]<array[s2]){
                tmp[k] = array[s1];
                k++;
                s1++;
            }else {
                tmp[k++] = array[s2++];
            }
        }

        //一方数组有剩余
        while(s1<=mid){
            tmp[k++]=array[s1++];
        }
        while(s2<=right){
            tmp[k++]=array[s2++];
        }

        //tmp数组内的值传回
        for (int i = 0; i < tmp.length; i++) {
            array[i+left] = tmp[i];
        }
    }


    //归并排序的非递归
    public static void mergeSortNor(int[] array){
        int gap =1;
        while(gap< array.length){
            for (int i = 0; i < array.length; i+= 2*gap) {
                int left = i;
                int mid = left+gap-1;
                int right = mid+gap;
                //避免越界
                if(mid>= array.length){
                    mid =array.length-1;
                }
                if(right<=array.length){
                    right = array.length-1;
                }
                //合并
                combine(array,left,right,mid);
            }
            gap *= 2;
        }
    }



    public static void main(String[] args) {
        MergeSort mergeSort = new MergeSort();
        int[] array ={2,54,12,1,11,65,4};
        mergeSort.merge(array);
        System.out.println(Arrays.toString(array));
    }
}
